package parser;

import java.util.Vector;

import net.rim.device.api.util.StringUtilities;

import beans.Update;

public class VersionParser {

	public VersionParser(){

	}

	public Update parseJSON(String json){
		if (json.equals("")){
			return null;
		} else {
			String[] splitJson = splitString(json, ",".charAt(0), false);
			String esObligatoria = splitJson[0].substring(splitJson[0].indexOf("\":")+2,splitJson[0].length());
			String fechaPublicacion = splitJson[1].substring(splitJson[1].indexOf("\":")+2,splitJson[1].length());
			String isLatest = splitJson[2].substring(splitJson[2].indexOf("\":")+2,splitJson[2].length());
			String linkUltimaVersion = splitJson[3].substring(splitJson[3].indexOf("\":")+3,splitJson[3].length()-1);
			linkUltimaVersion = StringUtilities.removeChars(linkUltimaVersion, "\\");
			String versionCompatible = splitJson[4].substring(splitJson[4].indexOf("\":")+2,splitJson[4].length()-1);
			return new Update(esObligatoria, fechaPublicacion, isLatest, linkUltimaVersion, versionCompatible);
		}
	}


	private String[] splitString(final String data, final char splitChar, final boolean allowEmpty)
	{
		Vector v = new Vector();

		int indexStart = 0;
		int indexEnd = data.indexOf(splitChar);
		if (indexEnd != -1)
		{
			while (indexEnd != -1)
			{
				String s = data.substring(indexStart, indexEnd);
				if (allowEmpty || s.length() > 0)
				{
					v.addElement(s);
				}
				indexStart = indexEnd + 1;
				indexEnd = data.indexOf(splitChar, indexStart);
			}

			if (indexStart != data.length())
			{
				// Add the rest of the string
				String s = data.substring(indexStart);
				if (allowEmpty || s.length() > 0)
				{
					v.addElement(s);
				}
			}
		}
		else
		{
			if (allowEmpty || data.length() > 0)
			{
				v.addElement(data);
			}
		}

		String[] result = new String[v.size()];
		v.copyInto(result);
		return result;
	}


}
